package com.fs.service.Impl;

import com.fs.dto.CartAddDTO;
import com.fs.entity.Cart;
import com.fs.mapper.CartMapper;
import com.fs.service.CartService;
import com.fs.vo.CartVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    /*添加购物车*/
    public void addToCart(Long userId, CartAddDTO cartAddDTO) {

        // 1. 检查该商品是否已在购物车中
        Cart existing = cartMapper.getCartByUserAndProduct(userId, cartAddDTO.getProductId());

        if (existing != null) {
            // 2. 已存在 → 数量 +1
            int newQuantity = existing.getQuantity() + cartAddDTO.getQuantity();
            existing.setQuantity(newQuantity);
            existing.setUpdateTime(LocalDateTime.now());
            cartMapper.updateCart(existing);
        } else {
            // 3. 不存在 → 新增记录
            Cart cart = Cart.builder()
                    .userId(userId)
                    .productId(cartAddDTO.getProductId())
                    .productName(cartAddDTO.getProductName())
                    .productImage(cartAddDTO.getProductImage())
                    .price(cartAddDTO.getPrice())
                    .quantity(cartAddDTO.getQuantity())
                    .checked(1)
                    .createTime(LocalDateTime.now())
                    .updateTime(LocalDateTime.now())
                    .build();

            cartMapper.insertCart(cart);
        }
    }


    /*查询购物车*/
    public List<CartVO> list(Long userId) {
        List<Cart> cartList = cartMapper.listByUserId(userId);

        // 将 Cart 转换为 CartVO，并计算 subtotal
        return cartList.stream().map(cart -> {
            return CartVO.builder()
                    .id(cart.getId())
                    .productId(cart.getProductId())
                    .productName(cart.getProductName())
                    .productImage(cart.getProductImage())
                    .price(BigDecimal.valueOf(cart.getPrice()))
                    .quantity(cart.getQuantity())
                    .checked(cart.getChecked())
                    .createTime(cart.getCreateTime())
                    .subtotal(BigDecimal.valueOf(cart.getPrice())
                            .multiply(BigDecimal.valueOf(cart.getQuantity())))
                    .build();
        }).collect(Collectors.toList());
    }



}
